#include "../include/muduo/proto/dispatcher.h"
#include "../include/muduo/proto/codec.h"
#include "../include/muduo/base/Logging.h"
#include "../include/muduo/base/Mutex.h"
#include "../include/muduo/net/EventLoop.h"
#include "../include/muduo/net/TcpClient.h"
#include "../include/muduo/base/CountDownLatch.h"
#include "../include/muduo/net/EventLoopThread.h"

#include <iostream>
#include <functional>   // bind()
#include <memory>
#include "request.pb.h"

using std::cout;
using std::endl;
using std::string;
using namespace std::placeholders;

class Client
{
public:
    using MessagePtr = std::shared_ptr<google::protobuf::Message>;
    using TranslateResponsePtr = std::shared_ptr<xzt::TranslateResponse>;
    using AddResponsePtr = std::shared_ptr<xzt::AddResponse>;


    Client(const string& sip, int port): _latch(1), _client(
        _loopthread.startLoop(), 
        muduo::net::InetAddress(sip, port), 
        "Client"),
        _dispatcher(
            std::bind(&Client::onUnKnownMessage, 
                    this, 
                    _1, _2, _3)),
        _codec(
            std::bind(&ProtobufDispatcher::onProtobufMessage,
                    &_dispatcher,
                    _1, _2, _3)
        )
    {
        // 注册业务处理函数
        _dispatcher.registerMessageCallback<xzt::TranslateResponse>(std::bind(
            &Client::onTranslate, this,
            _1, _2, _3
        ));
        _dispatcher.registerMessageCallback<xzt::AddResponse>(std::bind(
            &Client::onAdd, this,
            _1, _2, _3
        ));

        // 将类成员函数设置为服务器的回调处理函数
        _client.setConnectionCallback(std::bind(
            &Client::onConnection,
            this, _1
        ));

        _client.setMessageCallback(std::bind(
            &ProtobufCodec::onMessage, 
            &_codec, _1, _2, _3
        ));
    }

    void connect()
    {
        _client.connect();
        _latch.wait();
    }

    void Translate(const string& msg)
    {
        xzt::TranslateRequest req;
        req.set_msg(msg);
        if(!send(&req))
        {
            LOG_ERROR << "muduo::net::TcpConnectionPtr Client::_conn isnot connected";
        }
    }

    void Add(int num1, int num2)
    {
        xzt::AddRequest req;
        req.set_num1(num1);
        req.set_num2(num2);
        if(!send(&req))
        {
            LOG_ERROR << "muduo::net::TcpConnectionPtr Client::_conn isnot connected";
        }
    }


private:
    // 回调函数
    void onConnection(const muduo::net::TcpConnectionPtr& conn)
    {
        // 新连接建立成功时的回调函数
        if(conn->connected())
        {
            _latch.countDown();
            _conn = conn;
        }
        else{
            _conn.reset();
        }
    }

    void onUnKnownMessage(const muduo::net::TcpConnectionPtr& conn, const MessagePtr& message, muduo::Timestamp)
    {
        LOG_INFO << "onUnKnownMessage: " << message->GetTypeName();
    }

    void onTranslate(const muduo::net::TcpConnectionPtr& conn, const TranslateResponsePtr& message, muduo::Timestamp)
    {
        string rsp_msg = message->msg();
        LOG_INFO << "翻译结果：" << rsp_msg;
    }

    void onAdd(const muduo::net::TcpConnectionPtr& conn, const AddResponsePtr& message, muduo::Timestamp)
    {
        int result = message->result();
        LOG_INFO << "计算结果：" << result;
    }

    // 客户端->服务器 发送信息，类型为google::protobuf::Message
    bool send(const google::protobuf::Message* pmsg)
    {
        if(_conn->connected())
        {
            _codec.send(_conn, *pmsg);
            return true;
        }
        return false;
    }

private:
    // _loopthread是epoll的事件监控，会在子线程中进行描述符的事件监控，触发事件后进行io操作
    muduo::net::EventLoopThread _loopthread;
    // _client对象用于设置回调函数，告诉客户端收到什么请求该如何处理
    muduo::net::TcpClient _client;
    // _conn是客户端对应的连接
    muduo::net::TcpConnectionPtr _conn;
    // 为connect提供异步阻塞，用于实现同步
    muduo::CountDownLatch _latch;
    // 请求分发器
    ProtobufDispatcher _dispatcher;
    // 协议处理器
    ProtobufCodec _codec;
};

int main()
{
    Client client("127.0.0.1", 8085);
    client.connect();

    int n1 = 10, n2 = 40;
    client.Add(n1, n2);

    string word = "hello";
    //client.Translate(word);
    cout << "请输入待翻译的字符串：" << endl;
    while(true)
    {
        std::cin >> word;
        client.Translate(word);
    }

    sleep(5);

    return 0;
}